import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {AtSearchBar, AtIcon, AtSegmentedControl} from 'taro-ui'
import {View, Text, Navigator, Block, Checkbox, CheckboxGroup} from '@tarojs/components'
import {MySellerListItem, PlatformSet, UserIdentity} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {MY_SELLER_LIST, LIST_FIRST_SELLER, IDENTITY} from '../../constants/api'
import {user} from '../../utils/user.service'
import {platform} from '../../utils/platform-settting.service'
import {GetRequest, vcmonitor} from "../../utils/tools";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Index from "../components/water-mark/index";
import './list.scss'

interface MySellerListItemDiy extends MySellerListItem {
  selected?: boolean
}

export default class List extends Component {
  state: {
    index: number
    searchText: string
    loadMoreStatus: "more" | "loading" | "noMore"
    sellerList: MySellerListItemDiy[]
    noItem: boolean
    all: number // 运营中心进入为 1  生意经进入为 0
    userIdentity: UserIdentity | false
  } = {
    searchText: '',
    index: 0,
    loadMoreStatus: 'loading',
    sellerList: [],
    noItem: false,
    all: 0,
    userIdentity: false,
  }
  stage = ['本月', '上月', '全部']
  page = 1
  platformSet: PlatformSet | false = false

  async componentDidMount() {

    this.platformSet = await platform.getSetting()
    const all = parseInt(Taro.getCurrentInstance().router.params.all)

    Taro.showLoading({title: '加载中...'})
    const sellerList = await this.getData(this.page)
    if (sellerList) {
      if (sellerList.length === 0) {
        this.setState({noItem: true, sellerList, all})
      } else {
        this.setState({sellerList, all})
      }
    } else {
      this.setState({noItem: true, all})
    }
    setTimeout(() => {
      Taro.hideLoading()
    }, 100)
  }

  async componentDidShow() {
    Taro.setNavigationBarTitle({
      title: '我的' + process.env.fxName
    })
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
    const userIdentity = await http.get<UserIdentity>(IDENTITY, {})
    if (!userIdentity) {
      return
    }
    this.setState({userIdentity})

  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'}, async () => {
        this.page++
        const sellerList = await this.getData(this.page)
        const old = this.state.sellerList
        if (sellerList) {
          this.setState({sellerList: [...old, ...sellerList]})
        }
      })
    }
  }

  searchClick() {
    this.setState({sellerList: [], loadMoreStatus: 'loading'}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  searchChange(value) {
    this.setState({searchText: value})
  }

  clearSearch() {
    this.setState({sellerList: [], searchText: '', loadMoreStatus: 'loading'}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  typeChange(index) {
    this.setState({index, sellerList: [], loadMoreStatus: 'loading'}, async () => {
      this.page = 1
      const sellerList = await this.getData(this.page)
      if (sellerList) {
        if (sellerList.length === 0) {
          this.setState({noItem: true, sellerList})
        } else {
          this.setState({sellerList})
        }
      } else {
        this.setState({sellerList})
      }
    })
  }

  async getData(page) {
    const index = this.state.index
    const url = Taro.getCurrentInstance().router.params.all === '0' ? MY_SELLER_LIST : LIST_FIRST_SELLER
    const sellerList = await http.get<MySellerListItemDiy[]>(url, {
      pageNumber: page,
      dateFlag: this.stage[index],
      k: this.state.searchText
    })
    if (sellerList && sellerList.length === 10) {
      this.setState({loadMoreStatus: 'more'})
    } else {
      this.setState({loadMoreStatus: 'noMore'})
    }
    if (this.platformSet && this.platformSet.platformSellerType === 0) {
      sellerList && sellerList.forEach(item => {
        item.selected = false
      })
    }
    return sellerList
  }

  async secondry(id, name, count) {
    if (this.state.all === 1) {
      if (count > 0) {
        let mpkey = ''
        const uInfo = Taro.getStorageSync('user') || ''
        if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
          mpkey = uInfo.mpkey
        }
        Taro.navigateTo({url: `/distributor/list/children?id=${id}&name=${name}`+ '&mpkey=' + mpkey})
      } else {
        Taro.showToast({title: '没有下一级了', icon: 'none'})
      }
    }
  }

  checkChange(res) {
    const sellerList = this.state.sellerList.map(item => {
      if (res.detail.value.includes(String(item.id))) {
        item.selected = true
      } else {
        item.selected = false
      }
      return item
    })
    this.setState({sellerList})
  }

  selectAll() {
    const sellerList = this.state.sellerList.map(item => {
      item.selected = true
      return item
    })
    this.setState({sellerList})
  }

  gotoAdjust() {
    const sellerList = this.state.sellerList
    let selected: number[] = []
    if (sellerList.length > 0) {
      selected = sellerList.filter(i => i.selected).map(item => item.id)
    }
    if (selected.length > 0) {
      let mpkey = ''
      const uInfo = Taro.getStorageSync('user') || ''
      if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
        mpkey = uInfo.mpkey
      }
      if (selected.length === 1) {
        const selectUser = sellerList.find(item => item.id === selected[0])
        if (selectUser) {
          Taro.navigateTo({url: 'adjust-rate?selectedSellerId=' + selected.join(',') + '&rate=' + Math.floor(selectUser.rate * 100)+ '&mpkey=' + mpkey})
          return
        }
      }
      Taro.navigateTo({url: 'adjust-rate?selectedSellerId=' + selected.join(',')+ '&mpkey=' + mpkey})
    } else {
      Taro.showToast({title: '请先选择要操作的'+process.env.fxName, icon: 'none'})
    }
  }

  render() {
    const {searchText, index, sellerList, noItem, all, userIdentity} = this.state
    return (
      <View className='dist-list-root'>
        <GzhAuth />
        <Index />
        <AtSearchBar onClear={this.clearSearch.bind(this)} onActionClick={this.searchClick.bind(this)}
          value={searchText} onChange={this.searchChange.bind(this)}
        />
        <View className='header2'>
          <View className='title'>我的{process.env.fxName}</View>
          {/* <View className="all">全选</View> */}
          <View><AtSegmentedControl values={this.stage} onClick={this.typeChange.bind(this)}
            current={index}
          /></View>
        </View>
        <View className='select-all-box'>{this.platformSet && this.platformSet.platformSellerType === 0 && all === 0 &&
        <Text onClick={this.selectAll.bind(this)} className='select-all'>全选</Text>}</View>
        {sellerList.length > 0 && <CheckboxGroup onChange={this.checkChange.bind(this)} className='list-box'>
          {sellerList.length > 0 && sellerList.map(item => <View className='list-item heightAuto' key={item.id}>
            <View className='head'>
              {this.platformSet && this.platformSet.payVersion === 0 && this.platformSet.platformSellerType === 0 && all === 0 &&
              <Checkbox color={`${process.env.mainColor}`} value={String(item.id)} checked={item.selected} />}
              <View className='name-box' onClick={this.secondry.bind(this, item.id, item.real_name, item.team_count)}>
                {item.real_name && <Text className='name'>{item.real_name},</Text>}
                <Text className='phone'>{item.phone}</Text>
                {/*{this.platformSet && this.platformSet.platformSellerType === 0 && <Text className="rate">,返:{Math.floor(item.rate * 100)}%</Text>}*/}
              </View>
              <Navigator className='order-number'
                url={`/distributor/order/reseller-order?sid=` + item.id + '&dateFlag=' + this.stage[index]}
              ><AtIcon
                prefixClass='xxhz' value='fenxiaodingdan' size='16'
              /><Text
                decode
              > {item.off_order}单</Text></Navigator>
            </View>
            {all === 0 && <Block>
              <View className='stage'>
                <View className='stage-item'>{this.stage[this.state.index]}</View>
                <View className='stage-item'>总计</View>
              </View>
              <View className='statistics'>
                <View className='sta-box'>
                  <View className='number'>{item.self_range}</View>
                  <View className='label'>销售</View>
                </View>
                <View className='sta-box'>
                  <View className='number'>{item.rebate_range}</View>
                  <View className='label'>返利</View>
                </View>
                <View className='sta-box'>
                  <View className='number'>{item.self_all}</View>
                  <View className='label'>销售</View>
                </View>
                <View className='sta-box'>
                  <View className='number'>{item.rebate_all}</View>
                  <View className='label'>返利</View>
                </View>
              </View>
            </Block>}
            {all === 1 && <Block>
              <View className='all-title'>{this.stage[this.state.index]}</View>
              <View className='all-content'>
                <View className='all-item'>
                  <View className='number'>{item.team_count_range}</View>
                  <View className='label'>发展人数</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_range}</View>
                  <View className='label'>团队销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.self_range}</View>
                  <View className='label'>个人销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_rebate_range}</View>
                  <View className='label'>团队返利</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.rebate_range}</View>
                  <View className='label'>个人返利</View>
                </View>
              </View>
              <View className='all-title total'>总计</View>
              <View className='all-content'>
                <View className='all-item'>
                  <View className='number'>{item.team_count}</View>
                  <View className='label'>总团队人数</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_all}</View>
                  <View className='label'>团队总销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.self_all}</View>
                  <View className='label'>个人总销售额</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.team_rebate_all}</View>
                  <View className='label'>团队总返利</View>
                </View>
                <View className='all-item'>
                  <View className='number'>{item.rebate_all}</View>
                  <View className='label'>个人总返利</View>
                </View>
              </View>
            </Block>}
          </View>)}
        </CheckboxGroup>}
        {noItem && <View className='no-item'>
          <View className='tips'><Text decode>您还没有下属{process.env.fxName}&nbsp;</Text><Navigator
            url={`/common/distributor/invite/invite?sellerId=${userIdentity.sellerId}&sid=${userIdentity.siteId}&sourceUserId=${userIdentity.userId}`}
            className='link'
          >马上邀请</Navigator></View>
        </View>}
        {this.platformSet && this.platformSet.payVersion === 0 && this.platformSet.platformSellerType === 0 && all === 0 &&
        <View className='adjust-rate'><View className='btn' onClick={this.gotoAdjust.bind(this)}>更改比例</View></View>}
      </View>
    )
  }
}
